  import store from '@/store'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import storage from '@/utils/storage'
  import Config from '@/core/config'
  let timer = ''
  var socketTask = null
  var isClose = false
  let connectState = false; // 标记 WebSocket 连接状态
  let closeFlag = false; // 是否关闭socket
  let rec; //断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
  const wsUrl = Config.get('wsUrl')
  const init = () => {
		let that = this;
		console.log('调用连接websocket')
		socketTask = uni.connectSocket({
				url: `${wsUrl}?token=${storage.get(ACCESS_TOKEN)}&types=U`,
				// url: `wss://api.xueqianban.vip/wss?token=${storage.get(ACCESS_TOKEN)}&types=U`,
				header: {
					'content-type': 'application/json'
				},
				success(res) {
					console.log("websocket连接成功");
				},
				fail(err) {
					console.log("报错", err);
				}
		})
		socketTask.onOpen(function(res) {
			console.log('WebSocket连接已打开！');
			connectState = true
			isClose = false
			store.dispatch('handleConnectState', connectState)
			heart()
		})
		socketTask.onMessage(function(res) {
			console.log('收到服务器内容：' + res.data);
			handlerMsg(res) //这里是对获取到的数据进行操作
		})


		socketTask.onError(function(res) {
			console.log('WebSocket连接打开失败，请检查！');
			console.log(res);
			//进入重新连接
			socketError()

		})
		// // 监听连接关闭 -
		socketTask.onClose((e) => {
			console.log('WebSocket连接关闭！');
			// if (!that.isClose) {
			// 	reconnect()
			// }
			socketClose()
		})
		console.log(socketTask)
	}
	// websocket错误事件
    const socketError = () =>{
		closeSock({activeClose: true, isclose: false});
		reconnect()
	}
	
	const closeSock = ({activeClose = false, isclose = false}) => {
	    closeFlag = activeClose;
	    // 清除心跳定时器
	    clearInterval(timer);
	    timer = '';
	    // 清除重连定时器
	    rec && clearTimeout(rec);
		isClose = isclose
	    if (closeFlag && socketTask) {
	        // 关闭socket
	        socketTask.close();
	    }
	    // 初始化相关变量
	    socketTask = null;
	    connectState = false;
		store.dispatch('handleConnectState', connectState)
	}
	//进入重新连接
	const reconnect = () => {
	    console.log("尝试重新连接");
		if (connectState) return; //如果已经连上就不在重连了
		rec && clearTimeout(rec);
		rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
			if (!connectState && storage.get(ACCESS_TOKEN)) {
				init();
			}
		}, 5000);
		// this.socketTask.close();
	}
	const socketClose = () => {
		connectState = false;
		store.dispatch('handleConnectState', connectState)
		socketTask = null;
		closeFlag = false;
		clearInterval(timer);
		timer = '';
		// 清除重连定时器
		rec && clearTimeout(rec);
		if (!isClose) {
			reconnect()
		}
	}
	// 数据接收
	const handlerMsg = (msg) => {
	    console.log('接收消息', msg)
	    if (!msg || !msg.data) {
	        // 可能得情况 - 心跳机制、无关信息接收
	        console.log("收到数据：空消息");
	        return;
	    }
	
	    // 收到信息为Blob类型时
	    let result = JSON.parse(msg.data);
	    if (result.type === 0 || result.type === '0') {
	        //自己的业务
	    } else {
			store.dispatch('handleData', result)
	    }
	
	}
	
	//发送消息
	const sendSocketMsg = (msg) => {
		console.log('发送信息')
		console.log(msg)
		return new Promise((reslove, reject) => {
			socketTask.send({
				data: msg,
				success(res) {
					console.log('发送成功')
					reslove(res)
				},
				fail(res) {
					console.log('发送失败')
					console.log(res)
					reject(res)
				}
			});
		})
	}
				
	//心跳
	const heart = () => {
		let that = this;
		clearInterval(timer);
		timer = '';
		let msg = {
			"type": "heartbeat",
		}
		timer = setInterval(() => {
			 sendSocketMsg(JSON.stringify(msg)).then(res => {
				console.log('心跳成功')
			}).catch(res => {
				console.log('发送失败')
			console.log((res))
			 })
	
		}, 30000)
	}
	
export {sendSocketMsg, init, closeSock};